package com.ruike.alisurface.ui.answerQuestion;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.ui.answerQuestion.adapter.QuestionFragmentAdapter;
import com.ruike.alisurface.ui.answerQuestion.bean.AnswerQuestionBean;
import com.ruike.alisurface.ui.answerQuestion.bean.QuestionBean;
import com.ruike.alisurface.ui.answerQuestion.bean.ResultAnswerBean;
import com.ruike.alisurface.ui.answerQuestion.http.TongNuoHttp;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: voodoo
 * CreateDate: 2023/11/20 020上午 11:32
 * Description: 答题界面
 */
public class AnswerQuestionActivity extends BaseAty {

    @BindView(R.id.answerQuestionMain_viewPager_nsvp)
    NoScrollViewPager viewPager;
    @BindView(R.id.answerQuestionMain_nextQuestion_btn)
    Button nextQuestionBtn;

    List<ShowQuestionFragment> questionFragmentList;
    List<QuestionBean> questionBeanList;
    QuestionFragmentAdapter fragmentAdapter;

    List<AnswerQuestionBean.AnswerListBean> answerListBeans; // 回答的每一题的详情集合

    int questionShowTime = 60;
    int waitTime = 2;
    boolean isShowQuestionAnswer = false;
    MyCountDownTimer showOptionTimer; // 展示答案的倒计时

    TextView countdownTimeTv = null; // 这个是Fragment中的倒计时展示控件，到此处的目的是为了展示正确答案的倒计时

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_answer_question_main;
    }

    @Override
    protected void initViews() {
        initTitleBar(false);
    }

    @Override
    protected void initData() {
        questionShowTime = ShareUtils.getInstance().getInt(ShareKey.QUESTION_SHOW_TIME_KEY, 60); // 题目倒计时时长
        isShowQuestionAnswer = ShareUtils.getInstance().getBoolean(ShareKey.IS_SHOW_QUESTION_ANSWER_KEY, false); // 保存是否展示正确答案
        waitTime = ShareUtils.getInstance().getInt(ShareKey.ANSWER_SHOW_TIME_KEY, 2); // 展示正确答案时长
    }

    @Override
    protected void onStart() {
        super.onStart();
        showProgressDialog("正在请求题目，请稍候...");
        TongNuoHttp.getQuestionList(this);
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (TongNuoHttp.GET_QUESTION_LIST_URL.contentEquals(requestUrl)) {
            String questionJsonArrayStr = "[]";
            try {
                JSONObject resultJson = new JSONObject(requestJsonStr);
                JSONArray jsonArray = resultJson.optJSONArray("data");
                questionJsonArrayStr = jsonArray == null ? questionJsonArrayStr : jsonArray.toString();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            // 获取到题目列表
            questionBeanList = GsonUtils.jsonArray2ModelList(questionJsonArrayStr, QuestionBean.class);
            if (questionBeanList == null || questionBeanList.size() <= 0) {
                showErrorTip("当前获取的题目为空");
                startCountdownTimer(3, null, null);
                return;
            }
            // 设置展示的Fragment
            setQuestionFragment();
            ShareUtils.getInstance().putString(ShareKey.START_ANSWER_TIME, new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
            return;
        }
        if (TongNuoHttp.SUBMIT_ANSWER_URL.contentEquals(requestUrl)) {
            ResultAnswerBean resultAnswerBean = GsonUtils.json2Model(requestJsonStr, ResultAnswerBean.class);
            for (ShowQuestionFragment fragment : questionFragmentList) {
                fragment = null;
            }
            questionFragmentList.clear();

            Bundle bundle = new Bundle();
            bundle.putSerializable("resultAnswerBean", resultAnswerBean);
            startActivity(QuestionResultActivity.class, bundle);
            finish();
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (TongNuoHttp.GET_QUESTION_LIST_URL.contentEquals(requestUrl)) {
            showErrorTip(errorMsg);
            startCountdownTimer(3, null, null);
        }
        if (TongNuoHttp.SUBMIT_ANSWER_URL.contentEquals(requestUrl)) {
            showErrorTip(errorMsg);
            startCountdownTimer(3, null, null);
        }
    }

    @OnClick({R.id.answerQuestionMain_nextQuestion_btn})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.answerQuestionMain_nextQuestion_btn:
                nextQuestion();
                break;
        }
    }

    /**
     * 点击下一题按钮
     */
    public void nextQuestion() {
        int currentItem = viewPager.getCurrentItem();

        // 获取当前 Fragment
        ShowQuestionFragment currentFragment = questionFragmentList.get(currentItem);
        // 先通知 Fragment 中停止计时
        currentFragment.stopTime();
        // 获取Fragment中答题列表
        List<QuestionBean.OptionsBean> answerOptions = currentFragment.getAnswerOptions(isShowQuestionAnswer);
        // 获取题目当前索引的题目
        QuestionBean questionBean = questionBeanList.get(currentItem);

        // 创建提交对象的集合元素并将作答详情创建为提交的选项列表
        AnswerQuestionBean.AnswerListBean answerListBean = new AnswerQuestionBean.AnswerListBean();
        answerListBean.setQuestion_id(questionBean.getQuestion_id());
        answerListBean.setQuestion_index(questionBean.getQuestion_index());
        List<Integer> integerList = new ArrayList<>();
        for (QuestionBean.OptionsBean optionBean : answerOptions) {
            if (optionBean.isSelect()) {
                integerList.add(optionBean.getSort());
            }
        }
        answerListBean.setSubmit_answer(integerList);
        if (answerListBeans == null) {
            answerListBeans = new ArrayList<>();
        }
        answerListBeans.add(answerListBean);

        // 如果需要展示答题结果，那么直接启动倒计时
        if (isShowQuestionAnswer) {
            startShowOptionTimer(currentItem);
            return;
        }
        // 不需要展示的话就直接跳转即可
        fragmentJump(currentItem);
    }

    /**
     * 展示作答结果倒计时
     *
     * @param currentItem 当前展示的 item
     */
    private void startShowOptionTimer(int currentItem) {
        cancelShowOptionTimer();
        countdownTimeTv = questionFragmentList.get(currentItem).getCountdownTimeTv();
        nextQuestionBtn.setEnabled(false);
        showOptionTimer = new MyCountDownTimer(waitTime * 1000, 50) {
            @Override
            public void onTick(long millisUntilFinished) {
                countdownTimeTv.setText(String.valueOf(millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                countdownTimeTv = null;
                fragmentJump(currentItem);
            }
        };
        showOptionTimer.start();
    }

    /**
     * 跳转下一个Fragment或提交答案
     *
     * @param currentItem 当前展示的 item
     */
    private void fragmentJump(int currentItem) {
        currentItem++;
        if (currentItem >= questionBeanList.size() - 1) {
            nextQuestionBtn.setText("提交");
        }
        if (currentItem >= questionBeanList.size()) {
            showProgressDialog("正在提交答卷...");
            nextQuestionBtn.setVisibility(View.GONE);
            TongNuoHttp.submitAnswer(answerListBeans, this);
        } else {
            viewPager.setCurrentItem(currentItem, true);
        }
        nextQuestionBtn.setEnabled(true);
    }

    private void cancelShowOptionTimer() {
        if (showOptionTimer != null) {
            showOptionTimer.cancel();
            showOptionTimer = null;
        }
    }

    /**
     * 设置题目展示的 Fragment
     */
    private void setQuestionFragment() {
        questionFragmentList = new ArrayList<>();
        for (QuestionBean questionBean : questionBeanList) {
            ShowQuestionFragment fragment = new ShowQuestionFragment(questionBean, questionShowTime);
            questionFragmentList.add(fragment);
        }
        fragmentAdapter = new QuestionFragmentAdapter(getSupportFragmentManager(), questionFragmentList);
        viewPager.setAdapter(fragmentAdapter);
    }

}
